package net;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Only bother fetching a given page once.
 */
public class PageCache {
	static Map<URL, String> contentCache = new HashMap<URL, String>();
	static String fetch(URL address) throws IOException {
		synchronized(contentCache) {
			String value = contentCache.get(address);
			if (value != null)
				return value;
		}
		URLConnection conn = address.openConnection();
		InputStream is = conn.getInputStream();
		InputStreamReader isr = new InputStreamReader(is, "UTF-8");
		int ch;
		StringBuilder s = new StringBuilder();
		while ((ch = isr.read()) != -1)
			s.append((char)ch);
		String contents = s.toString();
		synchronized(contentCache) {
			contentCache.put(address, contents);
		}
		is.close();
		return contents;
	}
}
